package com.sifeng.test;

import java.io.*;
import java.util.Date;

/**
 * Created by yang_gsh on 2019/1/2.
 */
public class FileEncAndDec {
	private static final String  numOfEncAndDec = "1234567890"; //加密解密秘钥
	private static int dataOfFile = 0; //文件字节内容

	public static void main(String[] args) {

		File srcFile = new File("E:\\test.dat"); //初始文件
		File encFile = new File("E:\\test_enc.dat"); //加密文件
		File decFile = new File("E:\\test_dec.dat"); //解密文件
		String flg = "dec";

		try {
			ShowTime();
			if(flg.equals("dec")) {
				DecFile(encFile, decFile);
			} else {
				EncFile(srcFile, encFile); //加密操作
			}

			ShowTime();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private static void EncFile(File srcFile, File encFile) throws Exception {
		if (!srcFile.exists()) {
			System.out.println("source file not exixt");
			return;
		}

		if (!encFile.exists()) {
			System.out.println("encrypt file created");
			encFile.createNewFile();
		}
		InputStream fis = new FileInputStream(srcFile);
		OutputStream fos = new FileOutputStream(encFile);

		int j = 0;
		while ((dataOfFile = fis.read()) > -1) {
			if (j == numOfEncAndDec.length()) {
				j = 0;
			}
			fos.write(dataOfFile ^ numOfEncAndDec.charAt(j));
		}

		fis.close();
		fos.flush();
		fos.close();
	}

	private static void DecFile(File encFile, File decFile) throws Exception {
		if (!encFile.exists()) {
			System.out.println("encrypt file not exixt");
			return;
		}

		if (!decFile.exists()) {
			System.out.println("decrypt file created");
			decFile.createNewFile();
		}

		InputStream fis = new FileInputStream(encFile);
		OutputStream fos = new FileOutputStream(decFile);

		int j = 0;
		while ((dataOfFile = fis.read()) > -1) {
			if (j == numOfEncAndDec.length()) {
				j = 0;
			}
			fos.write(dataOfFile ^ numOfEncAndDec.charAt(j));
		}

		fis.close();
		fos.flush();
		fos.close();
	}

	public static void ShowTime(){
		Date date = new Date();
		long times = date.getTime();//时间戳
		System.out.println("time  : " + times);
	}
}
